import React, { useState, useRef, useEffect } from 'react';
import { useNavigate, Link, useLocation } from 'react-router-dom';
import ptLogo from '../../assets/pt-logo.png';
import CaptchaCanvas from '../../components/CaptchaCanvas';
import Toast from '../../components/Toast';
import './Login.css';
import { authService } from '../../services/auth';
import { isTokenValid } from '../../utils/auth';

const Login = () => {
  const navigate = useNavigate();
  const location = useLocation();
  const [formData, setFormData] = useState({ account: '', password: '', captcha: '' });
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');
  const [loading, setLoading] = useState(false);
  const captchaText = useRef('');
  const passwordInputRef = useRef(null);
  const captchaInputRef = useRef(null);
  const submitButtonRef = useRef(null);
  const captchaCanvasRef = useRef(null);

  const showToastMessage = (message) => {
    setToastMessage(message);
    setShowToast(true);
  };

  //token没过期自动登录
  useEffect(() => {
    const token = localStorage.getItem('token');
    if (token && isTokenValid(token)) {
      navigate('/user/profile');
    }
  }, [navigate]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  const handleCaptchaChange = (text) => {
    captchaText.current = text;
  };

  // 刷新验证码
  const refreshCaptcha = () => {
    if (captchaCanvasRef.current && captchaCanvasRef.current.refresh) {
      captchaCanvasRef.current.refresh();
      setFormData(prev => ({ ...prev, captcha: '' }));
    }
  };

  // 处理按键事件，支持回车键跳转到下一个输入框或提交表单
  const handleKeyDown = (e, field) => {
    if (e.key === 'Enter') {
      e.preventDefault();
      if (field === 'account') {
        passwordInputRef.current.focus();
      } else if (field === 'password') {
        captchaInputRef.current.focus();
      } else if (field === 'captcha') {
        handleSubmit(e);
      }
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (formData.captcha.trim().toUpperCase() !== captchaText.current.toUpperCase()) {
      showToastMessage('验证码错误');
      refreshCaptcha();
      return;
    }
    setLoading(true);
    try {
      const response = await authService.login(formData.account, formData.password);
      if (response.data.code === 200) {
        localStorage.setItem('token', response.data.data.token);
        localStorage.setItem('user', JSON.stringify(response.data.data.user));
        navigate('/categories');
      } else {
        showToastMessage(response.data.message || '登录失败，请重试');
        refreshCaptcha(); // 登录失败时刷新验证码
      }
    } catch (err) {
      showToastMessage(err.response?.data?.message || '登录失败，请重试');
      refreshCaptcha(); // 发生错误时刷新验证码
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="login-bg">
      <div className="login-card">
        <div className="login-header">
          <img src={ptLogo} alt="PT" className="pt-logo" />
          <span className="pt-title">PT种子站</span>
        </div>
        <div className="login-form">
          <h2>账号登录</h2>
          <form onSubmit={handleSubmit}>
            <div className="input-group">
              <label className="input-label">用户名/邮箱</label>
              <input
                className="input-box"
                type="text"
                name="account"
                autoComplete="username"
                value={formData.account}
                onChange={handleChange}
                onKeyDown={(e) => handleKeyDown(e, 'account')}
                required
                placeholder="请输入用户名或邮箱"
              />
            </div>
            <div className="input-group">
              <label className="input-label">密码</label>
              <input
                className="input-box"
                type="password"
                name="password"
                autoComplete="current-password"
                value={formData.password}
                onChange={handleChange}
                onKeyDown={(e) => handleKeyDown(e, 'password')}
                ref={passwordInputRef}
                required
                placeholder="请输入密码"
              />
            </div>
            <div className="input-group captcha-row">
              <input
                className="input-box"
                type="text"
                name="captcha"
                value={formData.captcha}
                onChange={handleChange}
                onKeyDown={(e) => handleKeyDown(e, 'captcha')}
                ref={captchaInputRef}
                required
                placeholder="请输入验证码"
                style={{ flex: 1 }}
              />
              <CaptchaCanvas 
                onChange={handleCaptchaChange} 
                ref={captchaCanvasRef}
              />
            </div>
            <button
              className="login-btn"
              type="submit"
              disabled={loading}
              ref={submitButtonRef}
            >
              {loading ? '登录中...' : '立即登录'}
            </button>
          </form>
          <div className="login-links">
            <Link to="/forgot-password">忘记密码？</Link>
            <Link to="/register">注册新账号</Link>
          </div>
        </div>
      </div>
      
      {showToast && (
        <Toast 
          message={toastMessage} 
          onClose={() => setShowToast(false)} 
        />
      )}
    </div>
  );
};

export default Login; 